package cn.xz.gobang.activity


import android.os.CountDownTimer
import cn.xz.gobang.R
import cn.xz.gobang.base.BaseActivity
import cn.xz.gobang.bean.*
import cn.xz.gobang.databinding.ActivityDoubleWelBinding
import cn.xz.gobang.dialog.StartPkDialog
import cn.xz.gobang.util.GetDataUtils
import cn.xz.gobang.util.JsonUtil
import cn.xz.gobang.util.SessionUtils
import cn.xz.gobang.util.ToastUtil
import java.util.*

/**
 * 多人对局匹配界面*/
class DoubleWelActivity: BaseActivity<ActivityDoubleWelBinding>(R.layout.activity_double_wel){

    //当前进入的房间号
    var mRoomCode = ""
    //是否是黑棋
    private var mType = true
    //当前加入房间的次数
    private var mJoinNum = 0
    //当前房间人数
    private var mRoomNum = -1
    //倒计时
    private var mCountDown10Timer: CountDownTimer? = null
    private var mCountDown15Timer: CountDownTimer? = null


    override fun initData() {
        //首先获取下多人房间列表
        GetDataUtils.onDoubleData(object :GetDataUtils.OnDoubleDataListener{
            override fun success(bean: RoomDouble) {
                //有房间，加入，如果循环加入两次，还不行，则创建房间
                if (mJoinNum == 2){
                    mJoinNum = 0
                    //创建房间
                    createRoom()
                }else{
                    joinRoom(bean)
                }
            }

            override fun error() {
                //无房间，创建房间
                createRoom()
            }

        })
    }

    private fun joinRoom(bean: RoomDouble){
        //随机选一个
        val x = Random().nextInt(bean.data.size)
        val mHomeBean = bean.data[x]
        mRoomCode = mHomeBean.roomID
        //修改列表数据
        if (mHomeBean.play1.size == 0){
            //1.如果白方没人，那我当白方
            mType = false
            mHomeBean.play1.add(CommonLib.getUserID)
        }else if (mHomeBean.play0.size == 1 && mHomeBean.play1.size == 1){
            //2.如果黑方，白方各有一个人，我随机选一个阵营
            val y = Random().nextInt(2)
            if (y == 1){
                //白方
                mType = false
                mHomeBean.play1.add(CommonLib.getUserID)
            }else{
                //黑方
                mType = true
                mHomeBean.play0.add(CommonLib.getUserID)
            }
            //3.有一个阵营已经两个人了，只能去另一个
        }else if (mHomeBean.play0.size == 2 && mHomeBean.play1.size == 1){
            //黑方满了，去白方
            mType = false
            mHomeBean.play1.add(CommonLib.getUserID)
        }else if (mHomeBean.play1.size == 2 && mHomeBean.play0.size == 1){
            //白方满了，去黑方
            mType = true
            mHomeBean.play0.add(CommonLib.getUserID)
        }else{
            //如果能走到这里，说明出差了，直接return 重新匹配
            mJoinNum++
            initData()
            return
        }
        mJoinNum = 0
        //修改列表数据
        GetDataUtils.upDataDoubleData(bean)
        //加入该房间
        GetDataUtils.onDoubleRoomData(mRoomCode,object :GetDataUtils.OnDoubleRoomListener{
            override fun success(bean: DoubleRoomData) {
                if (mType){
                    //黑
                    bean.play0.add(CommonLib.getUserID)
                }else{
                    bean.play1.add(CommonLib.getUserID)
                }
                GetDataUtils.onWriteData(mRoomCode,JsonUtil.serializeAsString(bean),object :GetDataUtils.OnWriteDataListener{
                    override fun success() {
                        //开启一个倒计时进入房间
                        open10()
                    }
                })
            }
            override fun error() {
                //如果能走到这里，说明出差了，直接return 重新匹配
                initData()
                return
            }
        })

    }

    private fun createRoom(){
        mRoomCode = CommonLib.DOUBLE_ROOM + CommonLib.getUserID

        mType = true
        //修改多人列表数据
        val mBody = RoomDouble()
        val mD = DoubleData()
        mD.roomID = mRoomCode
        mD.play0.add(CommonLib.getUserID)
        mBody.data.add(mD)
        GetDataUtils.upDataDoubleData(mBody)

        //创建多人房间
        val mRoomDouble= DoubleRoomData()
        mRoomDouble.play0.add(CommonLib.getUserID)
        GetDataUtils.onWriteData(mRoomCode,JsonUtil.serializeAsString(mRoomDouble),object :GetDataUtils.OnWriteDataListener{
            override fun success() {
                //开启倒计时
                runOnUiThread {
                    open15()
                }
            }
        })

    }

    private fun open15(){
        //开启15秒倒计时
        mCountDown15Timer = object : CountDownTimer(16 * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                mDataBind.tvDTime.post {
                    mDataBind.tvDTime.text = "匹配玩家倒计时${millisUntilFinished/1000}S"
                }
                GetDataUtils.onDoubleRoomData(mRoomCode,object :GetDataUtils.OnDoubleRoomListener{
                    override fun success(bean: DoubleRoomData) {
                        //我是黑方，查看白方是否有人了，有人则开始倒计时进入房间
                        mDataBind.tv01.post {
                            if (bean.play1.size > 0){
                                //开启进入房间倒计时
                                open10()
                                cancel()
                            }
                            //填充名字
                            if (bean.play0.isNotEmpty()){
                                mDataBind.tv01.text = bean.play0[0]
                                if (bean.play0.size == 2){
                                    mDataBind.tv02.text = bean.play0[1]
                                }
                            }
                            if (bean.play1.isNotEmpty()){
                                mDataBind.tv11.text = bean.play1[0]
                                if (bean.play1.size == 2){
                                    mDataBind.tv12.text = bean.play1[1]
                                }
                            }
                        }
                    }

                    override fun error() {
                        //报错取消倒计时，走倒计时结束
                        cancel()
                        //删除服务器对应数据
                        removeData()
                        //倒计时结束，没人销毁
                        finish()
                    }
                })
            }

            override fun onFinish() {
                //删除服务器对应数据
                removeData()
                //倒计时结束，没人销毁
                finish()
            }
        }.start()
    }

    private fun open10(){
        mRoomNum = -1
        runOnUiThread {
            //开启10秒倒计时
            mCountDown10Timer = object : CountDownTimer(11 * 1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    mDataBind.tvDTime.post {
                        mDataBind.tvDTime.text = "进入房间倒计时${millisUntilFinished/1000}S"
                    }
                    GetDataUtils.onDoubleRoomData(mRoomCode,object :GetDataUtils.OnDoubleRoomListener{
                        override fun success(bean: DoubleRoomData) {
                            //我是黑方，查看白方是否有人了，有人则开始倒计时进入房间
                            mDataBind.tv01.post {
                                //填充名字
                                if (bean.play0.isNotEmpty()){
                                    mDataBind.tv01.text = bean.play0[0]
                                    if (bean.play0.size == 2){
                                        mDataBind.tv02.text = bean.play0[1]
                                    }else{
                                        mDataBind.tv02.text = "等待"
                                    }
                                }
                                if (bean.play1.isNotEmpty()){
                                    mDataBind.tv11.text = bean.play1[0]
                                    if (bean.play1.size == 2){
                                        mDataBind.tv12.text = bean.play1[1]
                                    }else{
                                        mDataBind.tv12.text = "等待"
                                    }
                                }
                                //已经准备进入房间了，此时如果阵营中有一方人数为0，则退出
                                if (bean.play0.size == 0 || bean.play1.size == 0){
                                    ToastUtil.show("当前有一方阵营不足一人，无法开启对弈~")
                                    cancel()
                                    removeData()
                                    finish()
                                    return@post
                                }

                                //如果来新人了，重新倒计时
                                if(mRoomNum != -1 && mRoomNum != (bean.play0.size + bean.play1.size)){
                                    mCountDown10Timer!!.cancel()
                                    mCountDown10Timer = null
                                    open10()
                                    return@post
                                }
                                mRoomNum = bean.play0.size + bean.play1.size

                            }
                        }

                        override fun error() {

                        }
                    })
                }

                override fun onFinish() {
                    //倒计时结束进入房间
                    ToastUtil.show("232")
                    GetDataUtils.onDoubleData(object :GetDataUtils.OnDoubleDataListener {
                        override fun success(bean: RoomDouble) {
                            var mBean: DoubleData? = null
                            bean.data.forEach {
                                if (it.roomID == mRoomCode){
                                    mBean = it
                                }
                            }
                            bean.data.remove(mBean)
                            GetDataUtils.upDataDoubleData(bean)
                        }
                        override fun error() {
                        }
                    })

                }
            }.start()
        }
    }

    //删除数据
    //1.查询多人房间列表，并删除里面我创建的房间号
    //2.删除我创建的下棋列表
    private fun removeData(){
        GetDataUtils.onDoubleData(object :GetDataUtils.OnDoubleDataListener {
            override fun success(bean: RoomDouble) {
                var mBean: DoubleData? = null
                bean.data.forEach {
                    if (it.roomID == mRoomCode){
                        mBean = it
                    }
                }
                bean.data.remove(mBean)
                GetDataUtils.upDataDoubleData(bean)
            }

            override fun error() {
            }
        })
        //删除房间文件
        GetDataUtils.deleteRoom(mRoomCode)
    }

    override fun initEvent() {
        mDataBind.llcBack.setOnClickListener {
            if (mCountDown10Timer != null){
                mCountDown10Timer!!.cancel()
                mCountDown10Timer = null
            }
            //如果当前人数等于 1 或者 -1
            //删除列表数据 和房间，否则只删房间里我的数据
            if (mRoomNum == 1 || mRoomNum == -1){
                removeData()
            }else{
                GetDataUtils.onDoubleRoomData(mRoomCode,object :GetDataUtils.OnDoubleRoomListener{
                    override fun success(bean: DoubleRoomData) {
                        if (mType){
                            //黑
                            bean.play0.remove(CommonLib.getUserID)
                        }else{
                            bean.play1.remove(CommonLib.getUserID)
                        }
                        GetDataUtils.onWriteData(mRoomCode,JsonUtil.serializeAsString(bean),object :GetDataUtils.OnWriteDataListener{
                            override fun success() {
                            }
                        })
                    }
                    override fun error() {
                    }
                })
            }
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mCountDown10Timer != null){
            mCountDown10Timer!!.cancel()
            mCountDown10Timer = null
        }
        if (mCountDown15Timer != null){
            mCountDown15Timer!!.cancel()
            mCountDown15Timer = null
        }
    }
}